﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Core.Models;

namespace Core.Controllers
{
    [Permission("Can Administer Tags")]
    public class TagCategoryController : Controller
    {
        //
        // GET: /TagCategory/

        public ActionResult Index()
        {
            CoreEntities core = new CoreEntities();
            ViewBag.BusinessUnitId = (Guid)Session["BusinessUnitId"];
            return View();
        }

        //
        // POST: /TCList/

        [HttpPost]
        public JsonResult TCList(FormCollection collection)
        {
            CoreEntities core = new CoreEntities();
            Guid BUId = new Guid(collection.GetValues("BusinessUnitId")[0].ToString());
            int SkipRecs = int.Parse(collection.GetValues("iDisplayStart")[0].ToString());
            int TakeCount = int.Parse(collection.GetValues("iDisplayLength")[0].ToString());
            string strSearch = collection.GetValues("sSearch")[0].ToString();
            DataTableResponse r = new DataTableResponse();
            // Needs update when paging & sorting is implemented
            List<TagCategory> list = core.TagCategories.Where(m => (m.BusinessUnitId == BUId && m.TagCategoryName.Contains(strSearch) && m.IsDroppedYN == "N")).OrderBy(m => m.TagCategoryName).Skip(SkipRecs).Take(TakeCount).ToList();
            r.sEcho = collection.GetValues("sEcho")[0].ToString();
            // This query is required because the earlier query returns results for only 1 page.
            r.iTotalRecords = core.TagCategories.Where(m => (m.BusinessUnitId == BUId && m.TagCategoryName.Contains(strSearch) && m.IsDroppedYN == "N")).Count();
            r.iTotalDisplayRecords = r.iTotalRecords;
            foreach (TagCategory tc in list)
            {
                List<string> r1 = new List<string>();
                string editurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"editlink\" title=\"{1}\" >Edit</a>", "TagCategory", "Edit", tc.TagCategoryId.ToString());
                string detailsurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"detailslink\" title=\"{1}\" >Details</a>", "TagCategory", "Details", tc.TagCategoryId.ToString());
                string deleteurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"deletelink\" title=\"{1}\" >Delete</a>", "TagCategory", "Delete", tc.TagCategoryId.ToString());
                string tagsurl = String.Format("<a href=\"/{0}/{1}/{2}\" >Tags</a>", "Tag", "Index", tc.TagCategoryId.ToString());
                r1.Add(editurl + detailsurl + deleteurl + tagsurl);
                r1.Add(tc.TagCategoryName);
                r1.Add(String.Format("{0:g}", tc.ModifiedDT));
                r1.Add(tc.ModifiedByName);
/*                r1.Add(String.Format("{0:g}", tc.CreateDT));
                r1.Add(tc.CreatedByName); */
                r.aaData.Add(r1);
            }
            return Json(r);
        }

        public ActionResult DomainIndex()
        {
            return View();
        }

        //
        // POST: /DomainTCList/

        [HttpPost]
        public JsonResult DomainTCList(FormCollection collection)
        {
            CoreEntities core = new CoreEntities();
            int SkipRecs = int.Parse(collection.GetValues("iDisplayStart")[0].ToString());
            int TakeCount = int.Parse(collection.GetValues("iDisplayLength")[0].ToString());
            string strSearch = collection.GetValues("sSearch")[0].ToString();
            DataTableResponse r = new DataTableResponse();
            // Needs update when paging & sorting is implemented
            List<TagCategory> list = core.TagCategories.Where(m => (m.BusinessUnitId == null && m.TagCategoryName.Contains(strSearch) && m.IsDroppedYN == "N")).OrderBy(m => m.TagCategoryName).Skip(SkipRecs).Take(TakeCount).ToList();
            r.sEcho = collection.GetValues("sEcho")[0].ToString();
            // This query is required because the earlier query returns results for only 1 page.
            r.iTotalRecords = core.TagCategories.Where(m => (m.BusinessUnitId == null && m.TagCategoryName.Contains(strSearch) && m.IsDroppedYN == "N")).Count();
            r.iTotalDisplayRecords = r.iTotalRecords;
            foreach (TagCategory tc in list)
            {
                List<string> r1 = new List<string>();
                string editurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"editlink\" title=\"{1}\" >Edit</a>", "TagCategory", "Edit", tc.TagCategoryId.ToString());
                string detailsurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"detailslink\" title=\"{1}\" >Details</a>", "TagCategory", "Details", tc.TagCategoryId.ToString());
                string deleteurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"deletelink\" title=\"{1}\" >Delete</a>", "TagCategory", "Delete", tc.TagCategoryId.ToString());
                string tagsurl = String.Format("<a href=\"/{0}/{1}/{2}\" >Tags</a>", "Tag", "Index", tc.TagCategoryId.ToString());
                r1.Add(editurl + detailsurl + deleteurl + tagsurl);
                r1.Add(tc.TagCategoryName);
                r1.Add(String.Format("{0:g}", tc.ModifiedDT));
                r1.Add(tc.ModifiedByName);
/*                r1.Add(String.Format("{0:g}", tc.CreateDT));
                r1.Add(tc.CreatedByName); */
                r.aaData.Add(r1);
            }
            return Json(r);
        }

        //
        // GET: /TagCategory/Details/5

        public ActionResult Details(Guid id)
        {
            CoreEntities core = new CoreEntities();
            TagCategory tc = core.TagCategories.First(t => t.TagCategoryId == id);
            return View(tc);
        }

        //
        // GET: /TagCategory/Create

        public ActionResult Create(Guid id)
        {
            TagCategory tc = new TagCategory();
            tc.BusinessUnitId = id;
            return View(tc);
        } 

        //
        // POST: /TagCategory/Create

        [HttpPost]
        public ActionResult Create(TagCategory tc)
        {
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    tc.TagCategoryId = Guid.NewGuid();
                    if (tc.BusinessUnitId.Equals(Guid.Empty)) tc.BusinessUnitId = null;
                    tc.IsDroppedYN = "N";
                    tc.CreateDT = DateTime.Now;
                    tc.CreatedById = (Guid)Session["UserId"];
                    tc.CreatedByName = Session["UserFullName"].ToString();
                    tc.ModifiedDT = DateTime.Now;
                    tc.ModifiedById = (Guid)Session["UserId"];
                    tc.ModifiedByName = Session["UserFullName"].ToString();
                    CoreEntities core = new CoreEntities();
                    core.AddToTagCategories(tc);
                    core.SaveChanges();
                    if(tc.BusinessUnitId == null)
                        return RedirectToAction("DomainIndex");
                    else
                        return RedirectToAction("Index");
                }
                else
                    return View(tc);
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", Tools.ExceptionMessage(e));
                return View(tc);
            }
        }
        
        //
        // GET: /TagCategory/Edit/5
 
        public ActionResult Edit(Guid id)
        {
            CoreEntities core = new CoreEntities();
            TagCategory tc = core.TagCategories.First(t => t.TagCategoryId == id);
            return View(tc);
        }

        //
        // POST: /TagCategory/Edit/5

        [HttpPost]
        public ActionResult Edit(Guid id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    CoreEntities core = new CoreEntities();
                    TagCategory tc = core.TagCategories.First(b => b.TagCategoryId == id);
                    UpdateModel(tc, collection.ToValueProvider());
                    tc.ModifiedDT = DateTime.Now;
                    tc.ModifiedById = (Guid)Session["UserId"];
                    tc.ModifiedByName = Session["UserFullName"].ToString();
                    core.SaveChanges();
                    if (tc.BusinessUnitId == null)
                        return RedirectToAction("DomainIndex");
                    else
                        return RedirectToAction("Index");
                }
                else
                    return View();
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /TagCategory/Delete/5
 
        public ActionResult Delete(Guid id)
        {
            CoreEntities core = new CoreEntities();
            TagCategory tc = core.TagCategories.First(t => t.TagCategoryId == id);
            return View(tc);
        }

        //
        // POST: /TagCategory/Delete/5

        [HttpPost]
        public ActionResult Delete(Guid id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                if (ModelState.IsValid)
                {
                    CoreEntities core = new CoreEntities();
                    TagCategory tc = core.TagCategories.First(b => b.TagCategoryId == id);
                    tc.IsDroppedYN = "Y";
                    tc.ModifiedDT = DateTime.Now;
                    tc.ModifiedById = (Guid)Session["UserId"];
                    tc.ModifiedByName = Session["UserFullName"].ToString();
                    core.SaveChanges();
                    if (tc.BusinessUnitId == null)
                        return RedirectToAction("DomainIndex");
                    else
                        return RedirectToAction("Index");
                }
                else
                    return View();
            }
            catch
            {
                return View();
            }
        }
    }
}
